package chaowan.Controller;

import chaowan.Service.UserCartService;
import chaowan.pojo.CartVO;
import chaowan.pojo.ShopUser;
import chaowan.pojo.UserCart;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/cart")
public class UserCartController {

    @Resource
    private UserCartService userCartService;

    @GetMapping("/add/{gid}")
    public String addToCart(@PathVariable("gid") Long gid, HttpSession session) {
        ShopUser user = (ShopUser) session.getAttribute("loginUser");
        if (user == null) {
            return "redirect:/login.jsp?notLogin=true";
        }
        userCartService.addToCart(user.getUid(), gid);
        return "redirect:/cart/list";
    }

//    @GetMapping("/addForm")
//    public String addForm(Model model) {
//        model.addAttribute("cart", new UserCart());
//        return "cart/addForm";
//    }

//    @GetMapping("/editForm/{cartId}")
//    public String editForm(@PathVariable Long cartId, Model model) {
//        UserCart cart = userCartService.getCartById(cartId);
//        model.addAttribute("cart", cart);
//        return "cart/editForm"; // JSP 页面路径：/WEB-INF/views/cart/editForm.jsp
//    }

    @PostMapping("/add")
    public String add(UserCart userCart) {
        userCartService.save(userCart);
        return "redirect:/cart/list";
    }

    @PostMapping("/update")
    public String updateCart(@RequestParam Map<String, String> params, Model model) {
        Map<String, UserCart> cartMap = new HashMap<>();
        System.out.println(params);
        try {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                String key = entry.getKey();  // 如 userCarts[0].count
                String value = entry.getValue();

                if (!key.startsWith("userCarts[")) continue;

                int idx1 = key.indexOf('[');
                int idx2 = key.indexOf(']');
                String index = key.substring(idx1 + 1, idx2);  // 例如 0
                String field = key.substring(key.indexOf('.', idx2) + 1);  // 例如 count

                UserCart cart = cartMap.computeIfAbsent(index, k -> new UserCart());

                switch (field) {
                    case "cartId":
                        if (!value.isEmpty()) cart.setCartId(Long.parseLong(value));
                        break;
                    case "userId":
                        if (!value.isEmpty()) cart.setUserId(Long.parseLong(value));
                        break;
                    case "goodsId":
                        if (!value.isEmpty()) cart.setGoodsId(Long.parseLong(value));
                        break;
                    case "count":
                        if (!value.isEmpty()) cart.setCount(Integer.parseInt(value));
                        break;
                    case "checked":
                        cart.setChecked("1".equals(value) ? 1 : 0);
                        break;
                }
            }

            List<UserCart> cartList = new ArrayList<>(cartMap.values());
            System.out.println("更新购物车项数量：" + cartList.size());
            for (UserCart cart : cartList) {
                userCartService.update(cart);
            }

        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("error", "更新购物车失败：" + e.getMessage());
            return "cart";
        }

        return "redirect:/cart/list";
    }
    @GetMapping("/delete/{cartId}")
    public String delete(@PathVariable Long cartId) {
        userCartService.deleteById(cartId);
        return "redirect:/cart/list";
    }

    @GetMapping("/list")
    public String list(HttpSession session, Model model) {
        ShopUser user = (ShopUser) session.getAttribute("loginUser");
        List<CartVO> cartList = userCartService.getCartVOsByUserId(user.getUid());
        model.addAttribute("cartList", cartList);
        return "cart";
    }
}